#pragma once

#include "base_noncopyable.h"
#include <functional>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <future>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>

namespace El {
namespace Common {

class Task {
    DISALLOW_COPY_AND_MOVE(Task);

public:
    using TaskFunction = std::function<void()>;

    static Task& GetInstance();

    std::future<void> PushTask(const std::string& taskName, const TaskFunction& taskFunc);
    void SetThreadPoolSize(size_t size);

private:
    Task();
    ~Task();

    struct TaskItem {
        std::string name;
        TaskFunction func;
    };

    std::vector<std::thread> workers_;
    std::unordered_map<std::string, std::queue<TaskItem>> taskQueues_;
    std::unordered_set<std::string> processingTasks_;
    std::mutex queueMutex_;
    std::condition_variable condition_;
    bool stop_ = false;

    void initializeThreadPool(size_t size);
    void workerThread();
};

} // namespace Common
} // namespace El